/*
 * <p>Copyright® 2009-2022 东软 IT 实训中心版权所有。</p>
 */

package com.max.back.doctor.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.max.back.doctor.dao.PrescriptionItemDao;
import com.max.back.doctor.form.PrescriptionForm;
import com.max.back.doctor.form.PrescriptionItemForm;
import com.max.back.doctor.service.PrescriptionItemService;
import com.max.back.entity.PrescriptionItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 辛凤文 forward.seen@foxmail.com
 * @version 1.0
 * @description <p>
 * <code>PrescriptionItemServiceImpl</code>
 *
 * </p>
 * @time 2022/7/27 22:44
 * @see
 */
@Service("doctorPrescriptionItemService")
public class PrescriptionItemServiceImpl extends ServiceImpl<PrescriptionItemDao, PrescriptionItem>
        implements PrescriptionItemService {


    @Autowired
    private PrescriptionItemDao prescriptionItemDao;

    @Override
    public Boolean deleteAndCreatePrescriptionItems(PrescriptionForm prescription) {
        //  解析form数据
        String prescriptionId = prescription.getPrescriptionId();
        List<PrescriptionItemForm> prescriptionItemList = prescription.getPrescriptionItemList();
        //  删除所有处方相关
        Map<String, Object> deletePrescriptionItems = MapUtil.newHashMap();
        deletePrescriptionItems.put("prescription_Id", prescriptionId);
        boolean isRemoved = removeByMap(deletePrescriptionItems);
        //  事务批量添加所有处方小项
        List<PrescriptionItem> addPrescriptionItems = prescriptionItemList.stream().map(e -> {
            PrescriptionItem item = new PrescriptionItem();
            item.setId(IdUtil.simpleUUID());
            item.setPrescriptionId(prescriptionId);
            item.setDrugId(e.getDrugId());
            item.setDrugAmount(e.getDrugAmount());
            item.setDeleted(false);
            item.setDeliveryStatus(3001);
            item.setPayStatus(2002);
            return item;
        }).collect(Collectors.toList());
        boolean isSaved = saveBatch(addPrescriptionItems);
        // TODO 返回结果
        return isRemoved && isSaved;
    }

    @Override
    public List<Map<String, Object>> getSubmitPrescriptionItems(String prescriptionId) {
        return prescriptionItemDao.queryItemsByPrescriptionId(prescriptionId);
    }
}